package com.engc.common.utils;

import java.security.MessageDigest;

/**
 * MD5 加密工具类
 * @author 杨根华
 *
 */
public class MD5 {
	/**
	 * 将source字符串转换32位
	 * 加密的字符串
	 * 如果转换失败，将返回
     * null
	 * @param source       要加密的源字符串
	 * @return  md5String  32位加密的字符串
	 */
	public static String encodeToMd5(String source) {
		if(source==null)
			return null;
		
		try{
			MessageDigest md5=MessageDigest.getInstance("MD5");
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			
			char hexDigits[] = {
					'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
					'e', 'f'};
			
			byte[] strTemp=source.getBytes("utf-8");
			mdTemp.update(strTemp);
			
			byte[] md = mdTemp.digest();
			int k = 0;
			int j = md.length;char str[] = new char[j * 2];
			
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>>4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args){
		System.out.println(encodeToMd5("jifang"));
	}
}
